package org.ud;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * desc:
 *
 * @author Hongyi Zheng
 * @date 2024/3/13
 */
@Slf4j
@SpringBootApplication
public class HeroStoryApplication {

    @Value("${socket.port}")
    private int socketPort;

    public static void main(String[] args) {
        SpringApplication.run(HeroStoryApplication.class, args);
    }

    @Bean
    public CommandLineRunner nioServerStart() {
        return (args)->{
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(
                    new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new HttpServerCodec(),
                                    new HttpObjectAggregator(65535),
                                    new WebSocketServerProtocolHandler("/websocket")
                            );
                        }
                    }
            );
            try {
                ChannelFuture f = bootstrap.bind(socketPort).sync();
                if (f.isSuccess()) {
                    log.info("===============服务器已启动===============");
                }
                f.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                log.error("Exception:{}", ExceptionUtils.getStackTrace(e));
                Thread.currentThread().interrupt();
            }
        };
    }
}
